<template>
	<div id="img-crop" class="imgCrop">
		<x-header :left-options="{showBack: true}">
			<x-icon slot="overwrite-left" type="ios-arrow-back" size="30" class="backIcon" @click="goBack"></x-icon>
			<span slot="right" class="cropUse" @click="submit">使用</span>
		</x-header>
		<div class="cropComp">
			<crop-image-mobile
				:imageFile="file"
				:layerZIndex="20170424"
				:layerOpacity="1"
				layerColor="#000"
				:autoCompress="false"
				:quality="0.7"
				ref="cropImageMobile" />
		</div>
	</div>
</template>

<script>
	import axios from 'axios'
	import NetWorking from '../../../utils/networking'
	import bus from '@/event/eventBus'
	import {XHeader} from 'vux'
	export default {
		name: "img-crop",
		components: {
			XHeader
		},
		data() {
			return {
				url: this.$route.params.url,
				id: this.$route.params.id,
				file: this.$route.params.file,
				imageCorpUrl: "",
				fileId: '',
				now: Date.parse(new Date()) / 1000,
				expire: 0,
				policy: '',
				blob: ''
			};
		},
		created: function () {
			bus.$emit("barController", 9)
		},
		methods: {
			randomString(len = 32) {
				const chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
				const maxPos = chars.length;
				let pwd = '';
				for (let i = 0; i < len; i += 1) {
					pwd += chars.charAt(Math.floor(Math.random() * maxPos));
				}
				return pwd;
			},
			getSuffix(filename) {
				const pos = filename.lastIndexOf('.');
				let suffix = '';
				if (pos !== -1) {
					suffix = filename.substring(pos);
				}
				return suffix;
			},
			sendRequest() {
				const xmlhttp = new XMLHttpRequest();
				// 你的服务端接口地址:  参考demo:http://oss-demo.aliyuncs.com/oss-h5-upload-js-php/
				// 服务端签名后直传文档:  https://help.aliyun.com/document_detail/31926.html
				const serverUrl = 'http://www.edumavin.com:8080/api/oss/postpolicy';
				xmlhttp.open('GET', serverUrl, false);
				xmlhttp.setRequestHeader('Authorization', this.$store.state.user.token)
				xmlhttp.send(null);
				return xmlhttp.responseText;
			},
			getSignature() {
				// 可以判断当前expire是否超过了当前时间,如果超过了当前时间,就重新取一下.3s 做为缓冲
				this.now = Date.parse(new Date()) / 1000;
				if (this.expire < this.now + 3) {
					const body = this.sendRequest();
					const e = eval;
					const obj = e(`(${body})`);
					this.policy = obj.postpolicy;
					return true;
				}
				return false;
			},
			goBack() {
				this.$router.go(-1)
			},
			/*readBlobAsDataURL(blob, callback) {
				var a = new FileReader();
				a.onload = function(e) {callback(e.target.result);};
				a.readAsDataURL(blob);
			},*/
			submit() {
				this.$refs.cropImageMobile.cropImage(
					url => (
						this.imageCorpUrl = url
					))

				var xhr=new XMLHttpRequest(); //创建一个新的XHR对象
				xhr.open("GET",this.imageCorpUrl); //指定要获取内容的URL
				xhr.responseType="blob"; //以BLOB形式
				let _this = this
				xhr.onload=function(){ //onload比onstatechange更容易
					_this.blob = new Blob([xhr.response], {type: 'image/jpeg'});
					_this.uploadDataToOssWeb(_this.blob)
					/*_this.readBlobAsDataURL(_this.blob, function (dataurl){
						_this.uploadDataToOssWeb(dataurl)
					});*/
				};
				xhr.send(null);
			},
			uploadDataToOssWeb(dataUrl) {
				this.getSignature()
				const suffix = '.jpeg'
				let g_object_name = this.policy.dir + this.randomString(10) + suffix

				//We will use the FormData to upload the cropped image
				let fd = new FormData()
				fd.append('Content-Length', dataUrl.length)
				fd.append('OSSAccessKeyId', this.policy.accessid)
				fd.append('policy', this.policy.policy)
				fd.append('signature', this.policy.signature)
				fd.append('callback', this.policy.callback)

				//文件名字
				fd.append('key', g_object_name)
				fd.append('dir', this.policy.dir)
				fd.append('success_action_status','200')
				//文件必须声明在最后，否则异常
				fd.append('file', dataUrl)

				let _this = this

				return new Promise((resolve,reject)=>{
					axios.post(encodeURI(this.policy.host),fd,{
						headers: {
							'Content-Type': 'application/x-www-form-urlencoded'
						},
						transformRequest:function(data){
							return data;
						}
					}).then(res=>{
						resolve(res)
						_this.win(res.data)
					}).catch(err=>{
						reject(err);
					});
				});
			},
			win(obj) {
				NetWorking.doPatch(
					this.url,
					null,
					{
						id: this.id,
						head_img_id: obj.fileId
					},
					{
						params: {
							isCheckPwd: false
						}
					}
				).then(
					response => {
						let rs = response.data
						if(rs.error_code == 0){
							this.$store.commit('CREATE_USER_MODEL', rs.user_model)
							this.$router.go(-1)
						}else{
							alert(rs.error_message)
						}
					}
				)
			}
			/*uploadDataToOss(dataUrl) {
				this.getSignature()
				var options = new FileUploadOptions()
				options.fileKey = "file"
				//options.fileName = file.localURL.substr(file.localURL.lastIndexOf('/') + 1)
				options.fileName = 'head_img'
				options.mimeType = "image/jpeg"

				const suffix = '.jpeg'
				let g_object_name = this.policy.dir + this.randomString(10) + suffix

				const newMultipartParams = {
					key: g_object_name,
					policy: this.policy.policy,
					OSSAccessKeyId: this.policy.accessid,
					// 让服务端返回200,不然，默认会返回204
					success_action_status: '200',
					signature: this.policy.signature,
					callback: this.policy.callback,
				}

				options.params = newMultipartParams
				var ft = new FileTransfer()
				ft.upload(dataUrl, encodeURI(this.policy.host), this.win, this.fail, options)
			},*/
			/*fail(error) {
				alert(error)
			}*/
		}
	}
</script>

<style>
	#img-crop {
		font-family: "Avenir", Helvetica, Arial, sans-serif;
		-webkit-font-smoothing: antialiased;
		-moz-osx-font-smoothing: grayscale;
		text-align: center;
		color: #2c3e50;
	}
	body {
		margin: 0;
	}
	.uploadInput {
		display: none;
	}
	.corpBtn,
	.upload {
		border: 1px solid #1ba5fa;
		background-color: #1ba5fa;
		border-radius: 4px;
		width: 100px;
		height: 40px;
		color: #fff;
		font-size: 14px;
		text-align: center;
		line-height: 2;
		box-sizing: border-box;
		-webkit-box-sizing: border-box;
	}
	.showImage {
		width: 80px;
		height: 80px;
		border: 1px solid red;
		top: 10px;
		left: 5%;
	}
	.cropBar {
		display: flex;
		align-items: center;
		justify-content: space-around;
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		height: 100px;
	}
	.cropComp {
		position: absolute;
		left: 0;
		right: 0;
		top: 46px;
		bottom: 0;
	}

	.imgCrop > .vux-header {
		background: black !important;
	}

	.cropUse {
		color: lightblue;
		font-weight: bold;
		font-size: 13px;
	}
</style>